from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from django.http import HttpRequest, HttpResponse
from django.contrib.auth.decorators import login_required

def login_view(request: HttpRequest) -> HttpResponse:
    """
    处理用户登录请求的视图函数。
    Args:
    request (HttpRequest): Django的HttpRequest对象，包含请求信息。
    Returns:
    HttpResponse: Django的HttpResponse对象，包含响应信息。
    """
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            if not user.is_active:
                return render(request, 'login.html', {'error': '用户未启用，请联系管理员'})
            login(request, user)
            return redirect('/')  # 登录成功后跳转首页，可根据需要修改
        else:
            return render(request, 'login.html', {'error': '用户名或密码错误'})
    return render(request, 'login.html')

@login_required
def logout_view(request: HttpRequest) -> HttpResponse:
    """
    注销用户视图函数。
    Args:
    request (HttpRequest): HttpRequest 对象，包含请求信息。
    Returns:
    HttpResponse: 重定向到登录页面的 HttpResponse 对象。
    """
    logout(request)
    return redirect('/login/')
